<template>
  <div>
    <el-upload class="upload-demo" action="http://up-z1.qiniup.com" :on-preview="handlePreview"
      :on-remove="handleRemove" :before-remove="beforeRemove" :multiple="multiple" :limit="5" :on-exceed="handleExceed"
      :on-success="handleSuccess" :before-upload="handleBefore" :file-list="fileList" :data="qiniuData" :accept="accept"
      :show-file-list="false">
      <el-button size="small" type="primary">{{ text }}</el-button>
    </el-upload>
  </div>
</template>

<script>
import { getToken } from "@/api/qiniu";
export default {
  props: {
    text: {
      type: String,
      default: "上传图片",
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    accept: {
      type: String,
      default: '.jpg,.jpeg,.png,.gif',
    }
  },
  data() {
    return {
      loading: null,
      qiniuData: {
        token: "",
        key: "",
      },
      fileList: [],
    };
  },

  created() {
    this.getQiniuToken();
  },
  methods: {
    async getQiniuToken() {
      const res = await getToken();
      this.qiniuData.token = res.data.uptoken;
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleBefore(file) {
      this.loading = this.$loading({
        lock: true,
        background: 'rgb(0,0,0,0.5)'
      })
      const date = new Date();
      const year = date.getFullYear();
      const _moth = date.getMonth() + 1;
      const moth = _moth < 10 ? `0${_moth}` : _moth;
      const day = date.getDate();
      const timeStamp = Date.now();
      this.qiniuData.key = `${year}/${moth}${day}/${timeStamp}-${file.name}`;
    },
    handleSuccess(response, file, fileList) {
      console.log(response);
      console.log(file);
      console.log(fileList);
      this.loading.close();
      this.fileList = fileList;
      let urls = [];
      this.fileList.forEach(item => {
        if (item.response) {
          urls.push(`http://qiniu.disciplineeducation.com/${item.response.key}`)
        }
      })
      this.$emit("onSuccess", urls);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
  },
};
</script>

<style scoped>
.uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
</style>
